var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/boke";
function connect(callback){
    MongoClient.connect(url, { useNewUrlParser: true }, function(err, client) {
        if(err){
            console.log(err);
            return
        }else{
            let db = client.db('boke')
            callback(db)
        }

    });
}
module.exports = {
    find:function (collection,json,json2,callback) {
        connect(function (db) {
            let result = db.collection(collection).find(json).sort(json2).toArray(function (err,result) {
               if(err){
                   console.log(err);
                   return
               }else{
                   callback(result);
               }
            });

        })
    },
    findPage:function (collection,json,json2,tot,num,callback) {
        connect(function (db) {
            let result = db.collection(collection).find(json).sort(json2).skip(tot).limit(num).toArray(function (err,result) {
                if(err){
                    console.log(err);
                    return
                }else{
                    callback(result);
                }
            });

        })
    },
    insert:function (collection,json,callback) {
        connect(function (db) {
            let result = db.collection(collection).insertOne(json,function (err,result) {
                if(err){
                    console.log(err);
                    return
                }else{
                    callback(result);
                }
            });

        })
    },
    update:function (collection,json,json2,callback) {
        connect(function (db) {

            let result = db.collection(collection).updateOne(json,json2,function (err,result) {
                if(err){
                    console.log(err);
                    return
                }else{
                    callback(result);
                }
            });

        })
    },
    count:function (collection,json,callback) {
        connect(function (db) {
            json?json=json:json={};
            let result = db.collection(collection).countDocuments(json,function (err,result) {
                if(err){
                    console.log(err)
                }
                callback(result)
            });

        })
    },
    del:function (collection,json,callback) {
        connect(function (db) {
            let result = db.collection(collection).deleteOne(json,function (err,result) {
                if(err){
                    console.log(err);
                    return
                }else{
                    callback(result);
                }
            });

        })
    }
}

